package com.ad.aidai.fragments.my_order.my_send_order;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ad.aidai.R;
import com.ad.aidai.activitys.order_score.OrderScoreActivity;
import com.ad.aidai.base.BaseFragment;
import com.ad.aidai.bean.Order;
import com.ad.aidai.common.RxBus;
import com.ad.aidai.common.listener.RecyclerViewListener;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.events.CommonEvent;
import com.ad.aidai.fragments.my_order.MyOrderAdapter;
import com.ad.aidai.fragments.order_detail.OrderDetailFragment;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.DividerDecoration;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 我发的单页面
 * <p>
 * Created by Yusxon on 17/2/2.
 */

public class MySendOrderFragment extends BaseFragment implements MySendOrderContract.View, SwipeRefreshLayout
        .OnRefreshListener {

    @BindView(R.id.ercv_my_order)
    EasyRecyclerView ercvMyOrder;

    private MySendOrderContract.Presenter mPresenter;
    private MyOrderAdapter mAdapter;
    /**
     * 当前是否在刷新
     */
    private boolean isRefreshing = false;


    private LoadingDialog loadingDialog;
    private NormalDialog dialog;
    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;

    @Override
    protected void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_my_order, container, false);
        mView.setClickable(true);
    }

    @Override
    protected void initView() {
        //创建默认的线性LayoutManager
        ercvMyOrder.setLayoutManager(new LinearLayoutManager(getActivity()));

        //设置分割线
        DividerDecoration itemDecoration = new DividerDecoration(Color.parseColor("#F2F2F2"), 30, 0, 0);
        itemDecoration.setDrawLastItem(true);
        ercvMyOrder.addItemDecoration(itemDecoration);
        //监听下拉刷新
        ercvMyOrder.setRefreshListener(this);
        //设置下拉刷新控件的颜色,可以有颜色变化,下面的方法传入的参数可以多个的,一个就只显示一种颜色
        ercvMyOrder.setRefreshingColor(ContextCompat.getColor(mContext, R.color.colorTheme));

        mBasIn = new BounceTopEnter();
        mBasOut = new SlideTopExit();
    }

    @Override
    protected void initData() {
        new MySendOrderPresenter(mContext, this).subscribe();

        mAdapter = new MyOrderAdapter(mContext, mPresenter.getOrderData());
        mPresenter.setAdapter();
        ercvMyOrder.setAdapter(mAdapter);
        listener();
        //首次进界面,自动刷新
        ercvMyOrder.setRefreshing(true, true);
    }

    @Override
    public void setPresenter(MySendOrderContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @OnClick(R.id.iv_back)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onActivityBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh() {
        mPresenter.refresh();
    }

    private void listener() {

        mAdapter.setmOnItemSubClickListener(new RecyclerViewListener.OnRecyclerViewItemSubClickListener() {
            @Override
            public void onItemSubClick(View view, int position) {
                mPresenter.onItemSubClick(view, position);
            }
        });
        //加载更多
        mAdapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnMoreListener() {
            @Override
            public void onMoreShow() {
                if (!isRefreshing) {
                    mPresenter.loadMoreOrders();
                } else {
                    mAdapter.stopMore();
                }
            }

            @Override
            public void onMoreClick() {

            }

        });
        //没有更多
        mAdapter.setNoMore(R.layout.view_clickmore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                mAdapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                mAdapter.resumeMore();
            }
        });
        //加载错误(原来的逻辑有问题,暂时只能用没有更多来代替)
        mAdapter.setError(R.layout.view_nomore);

        mAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mPresenter.onItemClick(position);
                //跳转进item详细信息页面
                getActivity()
                        .getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(R.anim.fragment_slide_left_enter, 0, 0, R.anim
                                .fragment_slide_left_exit)
                        .add(android.R.id.content, new OrderDetailFragment(), "orderDetailed")
                        .addToBackStack("orderDetailed")
                        .commit();
            }
        });
    }

    @Override
    public void setOnRefresh(boolean refreshing) {
        this.isRefreshing = refreshing;
    }

    @Override
    public MyOrderAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void gotoComment() {
        mActivity.startActivity(new Intent(mActivity, OrderScoreActivity.class));
    }

    @Override
    public void showDialog(String message, final String btnText) {
        dialog = new NormalDialog(getContext());
        dialog.content(message)
                .style(NormalDialog.STYLE_TWO)
                .titleTextSize(20)
                .btnText("取消", btnText)
                .showAnim(mBasIn)
                .dismissAnim(mBasOut)
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mPresenter.clickDialogSure(btnText);
                        dialog.dismiss();
                    }
                });
    }

    @Override
    public void showLoading(@NonNull String text) {
        //显示加载对话框
        loadingDialog = new LoadingDialog(mActivity);
        loadingDialog.setLoadingText(text + "中...")
                .setFailedText(text + "失败")
                .setSuccessText(text + "成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    @Override
    public boolean onActivityBackPressed() {
        getFragmentManager().popBackStack();
        return false;
    }

    @Override
    protected void subscribeEvents() {
        //订阅事件
        addSubscription(RxBus.getInstance()
                .toObservable()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<Object>() {
                    @Override
                    public void call(Object event) {
                        if (event instanceof CommonEvent) {
                            CommonEvent commonEvent = (CommonEvent) event;
                            switch (commonEvent.getEvent()) {
                                case CommonEvent.ORDER_STATUS_CHANGE:
                                    mPresenter.orderStatusChange((Order) commonEvent.getData());
                                    break;
                            }
                        }
                    }
                })
                .subscribe(RxBus.defaultSubscriber()));

    }
}
